<template>
    <view class="login-container">
        <!-- 主要内容 -->
        <view class="main-content">
            <!-- 欢迎文字 -->
            <view class="welcome-section">
                <text class="welcome-title">欢迎回来</text>
                <text class="welcome-subtitle">登录以继续您的旅程。</text>
            </view>

            <!-- 表单区域 -->
            <view class="form-section">
                <!-- 手机号输入 -->
                <view class="form-item">
                    <view class="phone-input-container">
                        <input class="input" type="number" placeholder="手机号码" v-model="formData.mobile"
                            maxlength="11" />
                    </view>
                </view>

                <!-- 密码输入（仅在密码登录模式下显示） -->
                <view class="form-item" v-if="!isCodeLogin">
                    <input class="input" :type="showPassword ? 'text' : 'password'" placeholder="请输入密码"
                        v-model="formData.password" maxlength="20" />
                </view>

                <!-- 验证码输入（仅在验证码登录模式下显示） -->
                <view class="form-item" v-if="isCodeLogin">
                    <view class="code-input-container">
                        <input class="input code-input" type="number" placeholder="请输入验证码" v-model="formData.code"
                            maxlength="6" />
                        <button class="send-code-btn" :disabled="codeCountdown > 0" @click="sendSmsCode">
                            {{ codeCountdown > 0 ? `${codeCountdown}s` : '获取验证码' }}
                        </button>
                    </view>
                </view>

                <!-- 登录按钮 -->
                <button class="primary-btn" :disabled="!canLogin" @click="handleLogin">
                    {{ loginLoading ? '登录中...' : '登录' }}
                </button>
            </view>

            <!-- 注册按钮 -->
            <view class="form-item register">
                <text>没有账号？</text>
                <text @click="goToRegister" class="register-link">注册</text>
            </view>

            <!-- 分割线 -->
            <view class="divider">
                <view class="divider-text">或使用其他方式登录</view>
            </view>

            <!-- 微信登录 -->
            <view class="bottom-login-buttons">
                <!-- 验证码/密码登录切换按钮 -->
                <button class="code-login-btn" @click="toggleLoginMode">
                    <text>{{ isCodeLogin ? '密码登录' : '验证码登录' }}</text>
                </button>

                <!-- 微信登录按钮 -->
                <button class="wechat-btn" @click="handleWxLogin" :loading="wxLoginLoading">
                    <view class="wechat-icon">
                        <svg class="wechat-svg" fill="none" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path
                                d="M12 2C6.477 2 2 6.477 2 12C2 17.523 6.477 22 12 22C17.523 22 22 17.523 22 12C22 6.477 17.523 2 12 2ZM8.038 16.5C7.29 16.5 6.669 15.894 6.669 15.166C6.669 14.438 7.29 13.832 8.038 13.832C8.786 13.832 9.407 14.438 9.407 15.166C9.407 15.894 8.786 16.5 8.038 16.5ZM10.15 11.233C9.458 11.233 8.89 10.68 8.89 9.99C8.89 9.3 9.458 8.747 10.15 8.747C10.842 8.747 11.41 9.3 11.41 9.99C11.41 10.68 10.842 11.233 10.15 11.233ZM13.85 11.233C13.158 11.233 12.59 10.68 12.59 9.99C12.59 9.3 13.158 8.747 13.85 8.747C14.542 8.747 15.11 9.3 15.11 9.99C15.11 10.68 14.542 11.233 13.85 11.233ZM15.962 16.5C15.214 16.5 14.593 15.894 14.593 15.166C14.593 14.438 15.214 13.832 15.962 13.832C16.71 13.832 17.331 14.438 17.331 15.166C17.331 15.894 16.71 16.5 15.962 16.5Z"
                                fill="#09B65A"></path>
                        </svg>
                    </view>
                    <text>微信</text>
                </button>

            </view>
        </view>

        <!-- 底部 -->
        <view class="footer">
            <text>继续即表示您同意我们的 </text>
            <text class="footer-link" @click="showTerms">服务条款</text>
            <text> 和 </text>
            <text class="footer-link" @click="showPrivacy">隐私政策</text>
            <text>。</text>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            statusBarHeight: 0,
            loginType: 'password', // 'password' | 'sms'
            isCodeLogin: false, // 是否为验证码登录模式
            showPassword: false,
            loginLoading: false,
            wxLoginLoading: false,
            codeCountdown: 0,
            formData: {
                mobile: '',
                password: '',
                code: ''
            }
        }
    },

    computed: {
        canLogin() {
            if (this.isCodeLogin) {
                // 验证码登录模式
                return this.formData.mobile && this.formData.code;
            } else {
                // 密码登录模式
                return this.formData.mobile && this.formData.password;
            }
        }
    },

    onLoad() {
        // 获取状态栏高度
        const systemInfo = uni.getSystemInfoSync();
        this.statusBarHeight = systemInfo.statusBarHeight || 20;
    },

    methods: {
        // 切换登录方式
        switchLoginType(type) {
            this.loginType = type;
            this.formData.password = '';
            this.formData.code = '';
        },

        // 切换密码显示
        togglePassword() {
            this.showPassword = !this.showPassword;
        },

        // 发送短信验证码
        async sendSmsCode() {
            if (!this.formData.mobile) {
                uni.showToast({ title: '请输入手机号', icon: 'none' });
                return;
            }

            const mobileRegex = /^1[3-9]\d{9}$/;
            if (!mobileRegex.test(this.formData.mobile)) {
                uni.showToast({ title: '手机号格式错误', icon: 'none' });
                return;
            }

            try {
                const result = await uniCloud.callFunction({
                    name: 'send-sms',
                    data: {
                        mobile: this.formData.mobile,
                        type: 'login'
                    }
                });

                if (result.result.code === 200) {
                    uni.showToast({ title: '验证码发送成功', icon: 'success' });
                    this.startCountdown();
                } else {
                    uni.showToast({ title: result.result.message, icon: 'none' });
                }
            } catch (error) {
                uni.showToast({ title: '发送失败，请重试', icon: 'none' });
            }
        },

        // 开始倒计时
        startCountdown() {
            this.codeCountdown = 60;
            const timer = setInterval(() => {
                this.codeCountdown--;
                if (this.codeCountdown <= 0) {
                    clearInterval(timer);
                }
            }, 1000);
        },

        // 统一的登录模式切换方法
        toggleLoginMode() {
            if (this.isCodeLogin) {
                // 当前是验证码模式，切换到密码模式
                this.switchToPasswordLogin();
            } else {
                // 当前是密码模式，切换到验证码模式
                this.switchToCodeLogin();
            }
        },
        
        // 切换到验证码登录模式
        switchToCodeLogin() {
            this.isCodeLogin = true;
            this.loginType = 'sms';
            this.formData.password = '';
            this.formData.code = '';
        },
        
        // 切换到密码登录模式
        switchToPasswordLogin() {
            this.isCodeLogin = false;
            this.loginType = 'password';
            this.formData.password = '';
            this.formData.code = '';
        },

        // 普通登录
        async handleLogin() {
            if (!this.canLogin) return;

            this.loginLoading = true;

            try {
                const result = await uniCloud.callFunction({
                    name: 'user-login',
                    data: {
                        mobile: this.formData.mobile,
                        password: this.isCodeLogin ? '' : this.formData.password,
                        code: this.isCodeLogin ? this.formData.code : '',
                        loginType: this.isCodeLogin ? 'sms' : 'password'
                    }
                });

                if (result.result.code === 200) {
                    // 保存用户信息
                    uni.setStorageSync('userInfo', result.result.data);
                    uni.setStorageSync('token', result.result.data.token);

                    uni.showToast({ title: '登录成功', icon: 'success' });

                    setTimeout(() => {
                        uni.reLaunch({ url: '/pages/index/index' });
                    }, 1500);
                } else {
                    uni.showToast({ title: result.result.message, icon: 'none' });
                }
            } catch (error) {
                uni.showToast({ title: '登录失败，请重试', icon: 'none' });
            } finally {
                this.loginLoading = false;
            }
        },

        // 微信登录
        async handleWxLogin() {
            this.wxLoginLoading = true;

            try {
                // 获取微信授权
                const loginRes = await uni.login({ provider: 'weixin' });

                if (!loginRes.code) {
                    uni.showToast({ title: '微信授权失败', icon: 'none' });
                    return;
                }

                // 调用云函数
                const result = await uniCloud.callFunction({
                    name: 'wx-login',
                    data: {
                        code: loginRes.code
                    }
                });

                if (result.result.code === 200) {
                    // 登录成功
                    uni.setStorageSync('userInfo', result.result.data);
                    uni.setStorageSync('token', result.result.data.token);

                    uni.showToast({ title: '登录成功', icon: 'success' });

                    setTimeout(() => {
                        uni.reLaunch({ url: '/pages/index/index' });
                    }, 1500);
                } else if (result.result.code === 201) {
                    // 需要绑定手机号，跳转到注册页面
                    uni.navigateTo({
                        url: `/pages/register/register?openid=${result.result.data.openid}&fromWx=true`
                    });
                } else {
                    uni.showToast({ title: result.result.message, icon: 'none' });
                }
            } catch (error) {
                uni.showToast({ title: '微信登录失败', icon: 'none' });
            } finally {
                this.wxLoginLoading = false;
            }
        },

        // 跳转注册
        goToRegister() {
            uni.navigateTo({ url: '/pages/register/register' });
        },

        // 忘记密码
        forgetPassword() {
            uni.showToast({ title: '请联系客服重置密码', icon: 'none' });
        },

        // 返回上一页
        goBack() {
            uni.navigateBack();
        },

        // 显示服务条款
        showTerms() {
            uni.navigateTo({
                url: '/pages/privacy/privacy?type=terms'
            });
        },

        // 显示隐私政策
        showPrivacy() {
            uni.navigateTo({
                url: '/pages/privacy/privacy?type=privacy'
            });
        }
    }
}
</script>

<style scoped>
/* 主容器 */
.login-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    min-height: max(600px, 100vh);
    background-color: #f9fafb;
    font-family: 'Noto Sans SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

/* 头部 */
.header {
    display: flex;
    align-items: center;
    padding: 30rpx;
    padding-top: 10rpx;
    /* 基础内边距，动态高度由style属性控制 */
}

.back-btn {
    background: none;
    border: none;
    padding: 0;
    margin: 0;
    outline: none;
    cursor: pointer;
    transition: all 0.2s ease;
}

.back-btn:active {
    transform: scale(0.95);
    opacity: 0.7;
}

.back-icon-wrapper {
    width: 88rpx;
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.9);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    transition: all 0.2s ease;
}

.back-btn:hover .back-icon-wrapper {
    background-color: rgba(255, 255, 255, 1);
    box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.15);
}

.back-icon {
    font-size: 48rpx;
    color: #374151;
    font-weight: 600;
    line-height: 1;
    margin-left: -4rpx;
    /* 微调位置，让箭头看起来更居中 */
}

/* 主要内容 */
.main-content {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 0 48rpx;
}

/* 欢迎区域 */
.welcome-section {
    text-align: center;
    margin-bottom: 80rpx;
}

.welcome-title {
    display: block;
    font-size: 48rpx;
    font-weight: 700;
    color: #111827;
    letter-spacing: -0.025em;
    margin-bottom: 16rpx;
}

.welcome-subtitle {
    display: block;
    color: #6b7280;
    font-size: 32rpx;
    margin-top: 16rpx;
}

/* 表单区域 */
.form-section {
    margin-bottom: 64rpx;
}

.form-item {
    margin-bottom: 48rpx;
}

/* 手机号输入 */
.phone-input-container {
    position: relative;
}

.phone-input-container .input {
    padding-left: 100px;
}



.country-code {
    position: absolute;
    left: 32rpx;
    top: 50%;
    transform: translateY(-50%);
    font-size: 32rpx;
    color: #6b7280;
    z-index: 2;
}

.input {
    width: 100%;
    height: 96rpx;
    padding: 32rpx 32rpx 32rpx 112rpx;
    border: 1px solid #d1d5db;
    border-radius: 16rpx;
    background-color: #ffffff;
    font-size: 32rpx;
    color: #111827;
    box-sizing: border-box;
    transition: all 0.3s ease;
}

.input::placeholder {
    color: #9ca3af;
}

.input:focus {
    border-color: #1193d4;
    outline: none;
    box-shadow: 0 0 0 1px #1193d4;
}

/* 普通输入框（密码） */
.form-item .input {
    padding-left: 32rpx;
}

/* 登录方式切换 */
.login-type-switch {
    text-align: right;
    margin-bottom: 20rpx;
}

.switch-link {
    font-size: 28rpx;
    color: #1193d4;
    text-decoration: none;
}

/* 验证码输入容器 */
.code-input-container {
    display: flex;
    gap: 24rpx;
    align-items: center;
}

.code-input {
    flex: 1;
    padding-left: 32rpx !important;
}

.send-code-btn {
    height: 96rpx;
    padding: 0 32rpx;
    background-color: #1193d4;
    color: #ffffff;
    border: none;
    border-radius: 16rpx;
    font-size: 28rpx;
    white-space: nowrap;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    line-height: 1;
    text-align: center;
}

.send-code-btn[disabled] {
    background-color: #d1d5db;
    color: #9ca3af;
}

/* 继续按钮 */
.primary-btn {
    width: 100%;
    height: 96rpx;
    background-color: #1193d4;
    color: #ffffff;
    border: none;
    border-radius: 16rpx;
    font-size: 32rpx;
    font-weight: 700;
    transition: all 0.3s ease;
    box-shadow: 0 20rpx 50rpx rgba(17, 147, 212, 0.2);
}

.primary-btn:hover {
    background-color: rgba(17, 147, 212, 0.9);
}

.primary-btn[disabled] {
    background-color: #d1d5db;
    color: #9ca3af;
    box-shadow: none;
}

/* 分割线 */
.divider {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 64rpx 0;
}

.divider::before {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: 50%;
    height: 1px;
    background-color: #e5e7eb;
}

.divider-text {
    background-color: #f9fafb;
    padding: 0 24rpx;
    font-size: 28rpx;
    color: #6b7280;
    position: relative;
    z-index: 1;
}

/* 底部登录按钮组 */
.bottom-login-buttons {
    display: flex;
    gap: 24rpx;
    margin-bottom: 32rpx;
}

/* 验证码登录按钮 */
.code-login-btn {
    flex: 1;
    height: 96rpx;
    background-color: #ffffff;
    border: 1px solid #1193d4;
    border-radius: 16rpx;
    color: #1193d4;
    font-size: 32rpx;
    font-weight: 700;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    box-shadow: 0 2rpx 8rpx rgba(17, 147, 212, 0.1);
    line-height: 1;
}

.code-login-btn text {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

.code-login-btn:hover {
    background-color: #f0f9ff;
}

/* 微信登录按钮 */
.wechat-btn {
    flex: 1;
    height: 96rpx;
    background-color: #ffffff;
    border: 1px solid #d1d5db;
    border-radius: 16rpx;
    color: #374151;
    font-size: 32rpx;
    font-weight: 700;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16rpx;
    transition: all 0.3s ease;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
    line-height: 1;
}

.wechat-btn text {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

.wechat-btn:hover {
    background-color: #f3f4f6;
}

/* 注册按钮 */
.register {
    text-align:right;
    color: #374151;
}

.register-link:hover {
    font-size: 28rpx;
}
.register-link {
    color: #1193d4;
    text-decoration: none;
    font-weight: 700;
}


.wechat-icon {
    width: 48rpx;
    height: 48rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.wechat-svg {
    width: 48rpx;
    height: 48rpx;
}

/* 底部 */
.footer {
    text-align: center;
    padding: 48rpx;
    font-size: 28rpx;
    color: #9ca3af;
    line-height: 1.5;
}

.footer-link {
    color: #4b5563;
    font-weight: 500;
    text-decoration: none;
    transition: color 0.3s ease;
}

.footer-link:hover {
    color: #1193d4;
}
</style>